/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: HistoryEntrustFragmentPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.OpenOrderRequest;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.app.base.AppUI;
import io.bhex.baselib.constant.AppData;
import io.bhex.app.event.OrderFilterEvent;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.utils.ToastUtils;

/**
 * 描   述：历史委托单
 * ================================================
 */

public class HistoryEntrustFragmentPresenter extends BaseFragmentPresenter<HistoryEntrustFragmentPresenter.HistoryEntrustOrderUI> {

    private List<OrderBean> currentOrders=new ArrayList<>();
    private List<OrderBean> filterOrders=new ArrayList<>();
    private String orderPageId="";
    private boolean isVisible;
    private OrderFilterEvent currentFilter=new OrderFilterEvent();

    public void loadMore() {
        getHistoryEntrustOrders(true);
    }

    public interface HistoryEntrustOrderUI extends AppUI{

        void loadMoreComplete();

        void showOrders(List<OrderBean> currentOrders);

        void loadMoreFailed();

        void loadEnd();
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, HistoryEntrustFragmentPresenter.HistoryEntrustOrderUI ui) {
        super.onUIReady(activity, ui);
        getHistoryEntrustOrders(false);
    }


    @Override
    public void onResume() {
        EventBus.getDefault().register(this);

    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OrderFilterEvent event){
        if (isVisible) {
            filterOrder(event);
        }
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
    }


    /**
     * 过滤订单
     * @param event
     */
    private void filterOrder(OrderFilterEvent event) {
        currentFilter = event;
        orderPageId="";
        if (!currentOrders.isEmpty()) {
            currentOrders.clear();
            getUI().showOrders(currentOrders);
//            filterOrders.clear();
//            for (OrderBean orderBean : currentOrders) {
//                if (isMatchOrder(orderBean,event)) {
//                    filterOrders.add(orderBean);
//                }
//            }
//            getUI().showOrders(filterOrders);
        }

        getHistoryEntrustOrders(false);
    }

    private boolean isMatchOrder(OrderBean orderBean, OrderFilterEvent event) {
        if (!TextUtils.isEmpty(event.baseToken)) {
            if (!orderBean.getBaseTokenName().equalsIgnoreCase(event.baseToken)) {
                return false;
            }
        }
        if (!TextUtils.isEmpty(event.quoteToken)) {
            if (!orderBean.getQuoteTokenName().equalsIgnoreCase(event.quoteToken)) {
                return false;
            }
        }

        if (!TextUtils.isEmpty(event.orderStatus)) {
            if (!orderBean.getSide().equalsIgnoreCase(event.orderStatus)) {
                return false;
            }
        }
        if (!TextUtils.isEmpty(event.priceMode)) {
            return orderBean.getType().equalsIgnoreCase(event.priceMode);
        }

        return true;
    }

    /**
     * 获取当前委托
     *
     * @param isLoadMore
     */
    public void getHistoryEntrustOrders(final boolean isLoadMore) {
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(),getResources().getString(R.string.hint_network_not_connect));
            return;
        }


        if (isLoadMore) {
            if (currentOrders != null) {
                if (!currentOrders.isEmpty()) {
                    orderPageId = currentOrders.get(currentOrders.size() - 1).getOrderId();
                }
            }
        }


        OpenOrderRequest requestData = new OpenOrderRequest();
        requestData.baseToken = currentFilter.baseToken;
        requestData.quoteToken = currentFilter.quoteToken;
        requestData.orderStatus = currentFilter.orderStatus;
        requestData.priceMode = currentFilter.priceMode;
        if (isLoadMore && !TextUtils.isEmpty(orderPageId)) {
            //加载更多
            requestData.orderPageId = orderPageId;

        }

        TradeApi.RequestHistoryEntrustOrders(requestData, new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                getUI().loadMoreComplete();
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> data = response.getArray();
                    if (data != null) {
                        if (isLoadMore) {

                            if (data != null) {
                                currentOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                currentOrders.clear();
                                currentOrders = data;
                            }
                        }
                        getUI().showOrders(currentOrders);
                        if (data.size()< AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        }else{
                            getUI().loadMoreComplete();
                        }
                    }else{
                        getUI().loadMoreComplete();
                    }

                }else{
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

}
